package com.dingreading.cloud.mall.util;

import com.dingreading.cloud.common.util.DoubleUtil;
import com.dingreading.cloud.common.util.NepUtil;
import com.dingreading.cloud.mall.dto.ComboGoodsTypeDto;
import com.dingreading.cloud.mall.dto.GoodsTypeComboDto;
import org.apache.commons.collections4.CollectionUtils;

import java.util.*;

public class GoodsV3Util {

    /**
     * 获取组合商品的最低可售数量和总重量
     */
    public static ComboGoodsTypeDto getComboGoodsTypeDto(List<GoodsTypeComboDto> comboDtoList, Map<Long, Integer> stockNumMap, Map<Long, Integer> waitSendNumMap) {
        ComboGoodsTypeDto dto = new ComboGoodsTypeDto();
        if (CollectionUtils.isNotEmpty(comboDtoList)) {
            // 组合商品总重量
            double weight = 0;
            // 组合商品的最低可售数量集合
            Set<Integer> minBuyNumList = new HashSet<>();

            for (GoodsTypeComboDto comboDto : comboDtoList) {
                int stockNum = OrderFormV3Util.getGoodsTypeNum(stockNumMap.get(comboDto.getGoodsTypeId()), waitSendNumMap.get(comboDto.getGoodsTypeId()));
                // 套装内子商品的库存可售数量
                comboDto.setStockNum(stockNum);
                // 组合商品的最低可售数量=库存数量除以商品可购买数
                if (!minBuyNumList.contains(0))
                    minBuyNumList.add(stockNum / comboDto.getNum());
                //  组合商品重量
                weight = DoubleUtil.sum(weight, DoubleUtil.mul(comboDto.getNum(), NepUtil.nullToZero(comboDto.getWeight())));
            }

            // 获取最低可售数量
            if (CollectionUtils.isNotEmpty(minBuyNumList))
                dto.setSaleNum(Collections.min(minBuyNumList));
            else
                dto.setSaleNum(0);
            dto.setWeight(weight);
        }
        return dto;
    }

}
